from common.base_view import response_json
from common.const import CODE_OK
from common.lib_mysql import News


class Comment(News):
    def __init__(self):
        super().__init__()
        self.table = "users_comment"

    def list(self, page, id):
        table = self.table
        where_sql = ["new_id = {}".format(id)]
        res_name = "comments"
        size = 10
        info_sql = 'select {}.*, u.photo,u.id as user_id from {} left join users_users u on u.username = {}.username {}  order by updated desc limit {} OFFSET {}'
        total_sql = 'select count(*) as total from {} {}'
        if page <= 0:
            page = 1
        where = "where " + " and ".join(where_sql) if len(where_sql) else ""
        info_sql = info_sql.format(table, table, table, where, size, (page - 1) * size)
        total_sql = total_sql.format(table, where)
        print(info_sql, total_sql)
        users = self.exec_sql(info_sql)
        total = self.find_one(total_sql)
        return response_json(CODE_OK, {"total": total.get("total"), res_name: users})

    def delete(self, ids):
        return self.delete_func(self.table, ids)

    def insert(self, insert_dict):
        return self.insert_func(self.table, insert_dict)